﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Warehouse.API.Applcation.Command.InventoryCommand;
using Warehouse.Domain;
using Warehouse.Domain.DTO;
using Warehouse.Infrstructre;
using Warehouse.Infrstructre.Interface;
using static WMSpublic.ParseAPI;
using WMSpublic;
using System.ComponentModel.DataAnnotations;

namespace Warehouse.API.Applcation.CommandHandlers.InventoryCommandHandler
{
    /// <summary>
    /// 新增仓库盘点中介者
    /// </summary>
    public class ADDInventoryCommandHandler : IRequestHandler<ADDInventoryCommand, int>
    {
        private readonly IMapper _mapper;
        private readonly IInventoryRepository _inventoryRep;
        private readonly IInventProductRepository _InventPRep;
        private EFCoreDBcontext DB;

        public ADDInventoryCommandHandler(IMapper mapper, IInventoryRepository inventoryRep, IInventProductRepository inventPRep, EFCoreDBcontext dB)
        {
            _mapper = mapper;
            _inventoryRep = inventoryRep;
            _InventPRep = inventPRep;
            DB = dB;
        }

        public async Task<int> Handle(ADDInventoryCommand request, CancellationToken cancellationToken)
        {
            List<StockProducts> stocks = await GetStockProducts(1, 1000);//入库产品详情表
            using (var transaction = DB.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
            {
                try
                {
                    var s = _mapper.Map<Inventory>(request.dto);
                    //盘点表
                   await _inventoryRep.AddAsync(s);

                    //盘点产品关联表
                    foreach(var item in request.dto.AddInventGuan)
                    {
                            InventProduct product = new InventProduct()
                            {
                                Number = item.Number,
                                InventoryNumber = 0,
                                InventoryId = s.InventoryId,
                                ProductId = item.ProductId,
                                ProductName = item.ProductName,
                                ProductCode = item.ProductCode,
                                Specifications = item.Specifications,
                                Batch = item.Batch,
                                Unit = item.Unit,
                                WarehouseLocation = item.WarehouseLocation,
                                office_id = item.office_id,
                                user_id = item.user_id,
                                AddName = item.AddName,
                                AddTime = item.AddTime
                            };
                            await _InventPRep.AddAsync(product);
                    }
                    MessageCreateDto a = new MessageCreateDto();
                    a.AddName = "张三";
                    a.AddTime = DateTime.Now;
                    a.Description = "入库新增";
                    a.Title = "入库新增";
                    a.CurrenTime = DateTime.Now;
                    a.MessageType = "添加";
                    a.MessageState = false;
                    a.Office_Id = "1";
                    await MessageAdds(a);
                    //提交事务
                    await transaction.CommitAsync();
                    return 1;
                }
                catch (Exception)
                {
                    //回滚事务
                    transaction.Rollback();
                    throw;
                }
            }
        }
        public async Task<int> MessageAdds(MessageCreateDto a)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyNCIsInNpZCI6IjE4NTk4MDM1MDY2MzA4NTY3MDQiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMSIsImp0aSI6IjQzMzA2NmRmLWYyNjAtNDI2Ny1iYWY5LWJkMzgxZGVhZGMwYiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiLmnLHms4rpnJYiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy91cmkiOiIiLCJpc3MiOiJSZW5hb2JvMjAwNCIsImF1ZCI6IldlaWZ1d3UyMjAzQSJ9.E0PG5CbU-_2efHW14aTC5dmRc3FC7BLU0TIgjNsA1wo";
            HttpClientWrapper client = new HttpClientWrapper(token);
            string url = "http://116.205.121.197:8000/xxx/api/MessageCreate/CreateMessage";
            //将a转换为json字符串
            string jsonStr = JsonConvert.SerializeObject(a);
            string postRep = await client.PostAsync(url, jsonStr);
            return 1;
        }
        /// <summary>
        /// 入库产品关联信息表
        /// </summary>
        public class StockProducts
        {
            /// <summary>
            /// 入库产品id
            /// </summary>
            [Key]
            public int StockProductId { get; set; }
            /// <summary>
            /// 入库id
            /// </summary>
            public int? StockId { get; set; }
            /// <summary>
            /// 产品id
            /// </summary>
            public int? ProductsID { get; set; }
            /// <summary>
            /// 批次
            /// </summary>
            public string? Batch { get; set; }
            /// <summary>
            /// 单价
            /// </summary>
            public decimal? Sprice { get; set; }
            /// <summary>
            /// 入库数
            /// </summary>
            public int? Quantity { get; set; }
            /// <summary>
            /// 库位
            /// </summary>
            public int? Binlocation { get; set; }
            /// <summary>
            /// 状态
            /// </summary>
            public int? StateSP { get; set; }
            /// <summary>
            /// 审核人
            /// </summary>
            public string? ShenHePeople { get; set; }
            /// <summary>
            /// 审核时间
            /// </summary>
            public DateTime? ShenHeTime { get; set; }
            /// <summary>
            /// 公司id
            /// </summary>
            public string? office_id { get; set; }
            /// <summary>
            /// 用户id
            /// </summary>
            public int? user_id { get; set; }

        }

        /// <summary>
        /// 获取入库产品信息
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetStockProducts(int pageindex, int pagesize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwic2lkIjoiMTg1OTgwMzUwNjYzMDg1NjcwNCIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvZ3JvdXBzaWQiOiIxLDEsMSwxIiwianRpIjoiNDMzMDY2ZGYtZjI2MC00MjY3LWJhZjktYmQzODFkZWFkYzBiIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6IuWNouiKsyIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL3VyaSI6Ii8iLCJpc3MiOiJSZW5hb2JvMjAwNCIsImF1ZCI6IldlaWZ1d3UyMjAzQSJ9.sWP96tbSYf5jz3reVpvWkhrkHgM2U5YkHFmwk4E7_V0";

            HttpClientWrapper client = new HttpClientWrapper(token);
            string url = "http://116.205.121.197:8000/ckd/api/EnterStorages/GetWarehouseList?PageIndex=" + pageindex + "&PageSize=" + pagesize;
            string postRep = await client.GetAsync(url);
            var vendors = JsonConvert.DeserializeObject<ApiResultList<StockProducts>>(postRep);
            return vendors.data.list;
        }



















    }
}
